<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { Typography, Button, Menu, Table, Space, Input, Upload, Modal, Empty, message, Card, Spin, Statistic, Progress, Badge, Tabs } from 'ant-design-vue';
import {
  PlusOutlined,
  FolderOutlined,
  FileOutlined,
  SearchOutlined,
  InboxOutlined,
  UploadOutlined,
  DeleteOutlined,
  EditOutlined,
  InfoCircleOutlined,
  CloudUploadOutlined,
  FileTextOutlined,
  DashboardOutlined,
  AppstoreOutlined
} from '@ant-design/icons-vue';
import { useKnowledgeStore } from '../store/knowledgeStore';
import type { Document } from '../types';
import type { UploadChangeParam } from 'ant-design-vue/es/upload';
import type { Key } from 'ant-design-vue/es/table/interface';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const knowledgeStore = useKnowledgeStore();

// 状态
const searchValue = ref('');
const selectedCategory = ref('all');
const fileList = ref<any[]>([]);
const uploadModalVisible = ref(false);
const previewVisible = ref(false);
const previewDocument = ref<Document | null>(null);
const categoriesLoading = ref(false);
const documentsLoading = ref(false);
const activeTab = ref('documents'); // 'documents' or 'analytics'

// 挂载时获取数据
onMounted(async () => {
  categoriesLoading.value = true;
  documentsLoading.value = true;
  
  try {
    await knowledgeStore.fetchCategories();
    await knowledgeStore.fetchDocuments();
  } catch (error) {
    console.error('加载知识库数据失败:', error);
    message.error('加载知识库数据失败');
  } finally {
    categoriesLoading.value = false;
    documentsLoading.value = false;
  }
});

// 计算属性
const categories = computed(() => {
  const allCategories = [
    { key: 'all', title: '全部文档', icon: 'folder', count: undefined }
  ];
  
  if (knowledgeStore.categories.length > 0) {
    return [
      ...allCategories,
      ...knowledgeStore.categories.map(cate => ({
        key: cate.cateBizId,
        title: cate.name,
        icon: 'folder',
        count: cate.total
      }))
    ];
  }
  
  return allCategories;
});

const filteredDocuments = computed(() => {
  let docs = [...knowledgeStore.documents];
  
  // 根据分类筛选
  if (selectedCategory.value !== 'all') {
    docs = docs.filter(doc => doc.category === selectedCategory.value);
  }
  
  // 根据搜索关键词筛选
  if (searchValue.value.trim()) {
    const keyword = searchValue.value.toLowerCase();
    docs = docs.filter(doc => 
      doc.fileName.toLowerCase().includes(keyword) ||
      (doc.description && doc.description.toLowerCase().includes(keyword))
    );
  }
  
  return docs.map(doc => ({
    ...doc,
    key: doc.docBizId
  }));
});

// 统计数据
const statistics = computed(() => {
  const totalDocs = knowledgeStore.documents.length;
  const analyzedDocs = knowledgeStore.documents.filter(doc => doc.status === 1).length;
  const pendingDocs = totalDocs - analyzedDocs;
  const totalQAs = knowledgeStore.documents.reduce((sum, doc) => sum + parseInt(doc.qaNum), 0);
  
  const statusDistribution = [
    { status: '已完成', count: analyzedDocs, color: '#52c41a' },
    { status: '处理中', count: pendingDocs, color: '#faad14' }
  ];
  
  const categoryDistribution = categories.value
    .filter(cat => cat.key !== 'all' && cat.count !== undefined)
    .map(cat => ({
      name: cat.title,
      value: cat.count as number,
    }));
  
  return {
    totalDocs,
    analyzedDocs,
    pendingDocs,
    totalQAs,
    analyzedPercent: totalDocs ? Math.round((analyzedDocs / totalDocs) * 100) : 0,
    statusDistribution,
    categoryDistribution
  };
});

// 表格列定义
const columns = [
  {
    title: '文档名称',
    dataIndex: 'fileName',
    key: 'fileName',
    ellipsis: true
  },
  {
    title: '文件类型',
    dataIndex: 'fileType',
    key: 'fileType',
    width: 120
  },
  {
    title: '文件大小',
    dataIndex: 'size',
    key: 'size',
    width: 120,
    customRender: ({ text }: { text: string }) => formatFileSize(text)
  },
  {
    title: '问答数',
    dataIndex: 'qaNum',
    key: 'qaNum',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 120
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    width: 180,
    customRender: ({ text }: { text: string }) => formatDate(text)
  },
  {
    title: '操作',
    key: 'action',
    width: 180
  }
];

// 方法
const formatFileSize = (bytes: string): string => {
  if (!bytes) return '0 B';
  
  const units = ['B', 'KB', 'MB', 'GB'];
  let i = 0;
  let size = parseInt(bytes, 10);
  
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024;
    i++;
  }
  
  return `${size.toFixed(2)} ${units[i]}`;
};

const formatDate = (timestamp: string): string => {
  if (!timestamp) return '—';
  
  const date = new Date(timestamp);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

const handleCategorySelect = (info: any) => {
  selectedCategory.value = info.key.toString();
};

const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

const showUploadModal = () => {
  uploadModalVisible.value = true;
  fileList.value = [];
};

const handleUploadChange = (info: UploadChangeParam) => {
  fileList.value = info.fileList;
};

const beforeUpload = (file: File): boolean => {
  // 校验文件类型
  const isValidType = ['application/pdf', 'text/plain', 'application/msword', 
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type);
    
  if (!isValidType) {
    message.error('只支持上传PDF、TXT、DOC、DOCX格式文件');
  }
  
  // 校验文件大小，限制为20MB
  const isLessThan20M = file.size / 1024 / 1024 < 20;
  if (!isLessThan20M) {
    message.error('文件大小不能超过20MB');
  }
  
  return isValidType && isLessThan20M;
};

const handleUpload = async () => {
  if (fileList.value.length === 0) {
    message.warning('请选择要上传的文件');
    return;
  }
  
  try {
    await knowledgeStore.uploadDocuments(fileList.value, selectedCategory.value);
    message.success('文件上传成功');
    uploadModalVisible.value = false;
    fileList.value = [];
  } catch (error) {
    console.error('文件上传失败:', error);
    message.error('文件上传失败');
  }
};

const showDocumentPreview = (document: Record<string, any>) => {
  previewDocument.value = document as Document;
  previewVisible.value = true;
};

const deleteDocument = async (document: Record<string, any>) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除文档"${document.fileName}"吗？此操作不可恢复。`,
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await knowledgeStore.deleteDocument(document.docBizId);
        message.success('文档删除成功');
      } catch (error) {
        console.error('删除文档失败:', error);
        message.error('删除文档失败');
      }
    }
  });
};

// 添加自定义请求函数
const customRequest = (options: any) => {
  if (options.onSuccess) {
    options.onSuccess();
  }
};

// Tab切换
const handleTabChange = (activeKey: Key) => {
  activeTab.value = activeKey.toString();
};

// 获取最大值（确保不为空）
const getMaxValue = (values: number[]): number => {
  if (values.length === 0) return 1;
  return Math.max(...values);
};
</script>

<template>
  <div class="knowledge-container">
    <div class="knowledge-header">
      <div class="header-title">
        <Title :level="3" class="title-text">知识库管理</Title>
        <Text type="secondary">管理、组织和优化您的知识资源</Text>
      </div>
      <div class="header-actions">
        <Button type="primary" @click="showUploadModal" class="upload-btn">
          <CloudUploadOutlined />
          上传文档
        </Button>
      </div>
    </div>
    
    <div class="knowledge-tabs">
      <Tabs 
        v-model:activeKey="activeTab" 
        @change="handleTabChange" 
        class="custom-tabs"
      >
        <TabPane key="documents">
          <template #tab>
            <span>
              <FileTextOutlined />
              文档管理
            </span>
          </template>
        </TabPane>
        <TabPane key="analytics">
          <template #tab>
            <span>
              <DashboardOutlined />
              数据分析
            </span>
          </template>
        </TabPane>
      </Tabs>
    </div>
    
    <!-- 文档管理面板 -->
    <div v-if="activeTab === 'documents'" class="documents-panel">
      <div class="panel-layout">
        <!-- 左侧分类侧边栏 -->
        <div class="category-sidebar">
          <Card title="文档分类" class="category-card" :bordered="false">
            <template #extra>
              <Button type="link" size="small">
                <PlusOutlined />
              </Button>
            </template>
            <Spin :spinning="categoriesLoading">
              <Menu
                mode="inline"
                :selectedKeys="[selectedCategory]"
                @select="handleCategorySelect"
                class="category-menu"
              >
                <Menu.Item v-for="category in categories" :key="category.key" class="category-menu-item">
                  <template #icon>
                    <FolderOutlined />
                  </template>
                  <span class="category-name">{{ category.title }}</span>
                  <Badge 
                    v-if="category.count" 
                    :count="category.count" 
                    :numberStyle="{ backgroundColor: '#52c41a' }" 
                  />
                </Menu.Item>
              </Menu>
            </Spin>
          </Card>
        </div>
        
        <!-- 右侧文档列表 -->
        <div class="document-panel">
          <div class="filter-bar">
            <Input.Search
              v-model:value="searchValue"
              placeholder="搜索文档..."
              allowClear
              @search="handleSearch"
              class="search-input"
            />
          </div>
          
          <Spin :spinning="documentsLoading">
            <Table
              :columns="columns"
              :dataSource="filteredDocuments"
              rowKey="docBizId"
              :pagination="{
                pageSize: 10,
                showSizeChanger: true,
                showTotal: total => `共 ${total} 条记录`
              }"
              class="documents-table"
            >
              <template #bodyCell="{ column, record }">
                <!-- 文档名称列 -->
                <template v-if="column.key === 'fileName'">
                  <Space>
                    <FileOutlined />
                    <span>{{ record.fileName }}</span>
                  </Space>
                </template>
                
                <!-- 状态列 -->
                <template v-else-if="column.key === 'status'">
                  <Badge 
                    :status="record.status === 1 ? 'success' : 'processing'" 
                    :text="record.statusDesc" 
                  />
                </template>
                
                <!-- 操作列 -->
                <template v-else-if="column.key === 'action'">
                  <Space size="small">
                    <Button 
                      type="text" 
                      size="small" 
                      @click="showDocumentPreview(record)"
                    >
                      <InfoCircleOutlined />
                      查看
                    </Button>
                    <Button 
                      type="text" 
                      size="small" 
                      danger
                      @click="deleteDocument(record)"
                    >
                      <DeleteOutlined />
                      删除
                    </Button>
                  </Space>
                </template>
              </template>
              
              <template #emptyText>
                <Empty 
                  description="暂无文档" 
                  :image="Empty.PRESENTED_IMAGE_SIMPLE"
                  class="empty-docs"
                >
                  <Button type="primary" @click="showUploadModal">
                    <UploadOutlined />
                    上传文档
                  </Button>
                </Empty>
              </template>
            </Table>
          </Spin>
        </div>
      </div>
    </div>
    
    <!-- 数据分析面板 -->
    <div v-else-if="activeTab === 'analytics'" class="analytics-panel">
      <div class="stats-cards">
        <Card class="stat-card">
          <Statistic 
            title="文档总数" 
            :value="statistics.totalDocs" 
            :valueStyle="{ color: '#1890ff' }"
          >
            <template #prefix>
              <FileTextOutlined />
            </template>
          </Statistic>
        </Card>
        
        <Card class="stat-card">
          <Statistic 
            title="问答总数" 
            :value="statistics.totalQAs" 
            :valueStyle="{ color: '#52c41a' }"
          >
            <template #prefix>
              <InfoCircleOutlined />
            </template>
          </Statistic>
        </Card>
        
        <Card class="stat-card">
          <Statistic 
            title="处理完成" 
            :value="`${statistics.analyzedPercent}%`" 
            :valueStyle="{ color: '#722ed1' }"
          >
            <template #prefix>
              <AppstoreOutlined />
            </template>
          </Statistic>
          <Progress :percent="statistics.analyzedPercent" status="active" />
        </Card>
      </div>
      
      <div class="analytics-details">
        <Card title="文档状态分布" class="analytics-card">
          <template v-for="(item, index) in statistics.statusDistribution" :key="index">
            <div class="status-item">
              <div class="status-info">
                <Badge :color="item.color" />
                <span>{{ item.status }}</span>
              </div>
              <div class="status-count">{{ item.count }}</div>
            </div>
            <Progress 
              :percent="statistics.totalDocs ? (item.count / statistics.totalDocs * 100) : 0" 
              :strokeColor="item.color" 
              :showInfo="false" 
            />
          </template>
        </Card>
        
        <Card title="分类文档数量" class="analytics-card">
          <div v-if="statistics.categoryDistribution.length > 0">
            <div 
              v-for="(item, index) in statistics.categoryDistribution" 
              :key="index"
              class="category-stat-item"
            >
              <div class="category-name">{{ item.name }}</div>
              <div class="category-bar-container">
                <div 
                  class="category-bar" 
                  :style="{ 
                    width: `${(item.value / getMaxValue(statistics.categoryDistribution.map(i => i.value))) * 100}%`,
                    backgroundColor: `hsl(${210 + index * 30}, 70%, 60%)`
                  }"
                ></div>
                <span class="category-value">{{ item.value }}</span>
              </div>
            </div>
          </div>
          <Empty v-else description="暂无分类数据" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
        </Card>
      </div>
    </div>
    
    <!-- 上传模态框 -->
    <Modal
      v-model:visible="uploadModalVisible"
      title="上传文档"
      @ok="handleUpload"
      okText="上传"
      cancelText="取消"
      width="600px"
      class="upload-modal"
    >
      <Upload.Dragger
        v-model:fileList="fileList"
        :beforeUpload="beforeUpload"
        :multiple="true"
        @change="handleUploadChange"
        :showUploadList="true"
        :customRequest="customRequest"
        class="upload-dragger"
      >
        <p class="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
        <p class="ant-upload-hint">
          支持PDF、TXT、DOC、DOCX格式文件，单个文件不超过20MB
        </p>
      </Upload.Dragger>
    </Modal>
    
    <!-- 文档预览 -->
    <Modal
      v-model:visible="previewVisible"
      :title="previewDocument?.fileName"
      width="800px"
      :footer="null"
      class="preview-modal"
    >
      <div v-if="previewDocument" class="document-preview">
        <div class="document-info">
          <div class="info-row">
            <div class="info-label">文件类型:</div>
            <div class="info-value">{{ previewDocument.fileType }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">文件大小:</div>
            <div class="info-value">{{ formatFileSize(previewDocument.size) }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">上传时间:</div>
            <div class="info-value">{{ formatDate(previewDocument.createTime) }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">更新时间:</div>
            <div class="info-value">{{ formatDate(previewDocument.updateTime) }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">状态:</div>
            <div class="info-value">
              <Badge 
                :status="previewDocument.status === 1 ? 'success' : 'processing'" 
                :text="previewDocument.statusDesc" 
              />
            </div>
          </div>
          <div class="info-row">
            <div class="info-label">问答数:</div>
            <div class="info-value">{{ previewDocument.qaNum }}</div>
          </div>
        </div>
        
        <div v-if="previewDocument.content" class="document-content-preview">
          <Typography.Paragraph>
            {{ previewDocument.content }}
          </Typography.Paragraph>
        </div>
        <Empty v-else description="暂无预览内容" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.knowledge-container {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  background: #f9fafc;
  overflow: hidden;
}

.knowledge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: linear-gradient(90deg, #1890ff, #0050b3);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.header-title {
  display: flex;
  flex-direction: column;
}

.title-text {
  color: white !important;
  margin: 0 !important;
}

.header-title :deep(.ant-typography) {
  color: rgba(255, 255, 255, 0.85);
  margin: 4px 0 0 0;
}

.upload-btn {
  background: white;
  color: #1890ff;
  border: none;
  font-weight: 500;
  height: 40px;
  padding: 0 24px;
  border-radius: 20px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.upload-btn:hover {
  background: #f5f5f5;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.knowledge-tabs {
  padding: 0 24px;
  background: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.custom-tabs :deep(.ant-tabs-tab) {
  padding: 12px 16px;
  font-size: 15px;
}

.custom-tabs :deep(.ant-tabs-tab .anticon) {
  margin-right: 8px;
}

.custom-tabs :deep(.ant-tabs-ink-bar) {
  background: #1890ff;
  height: 3px;
  border-radius: 3px 3px 0 0;
}

.panel-layout {
  display: flex;
  height: calc(100vh - 165px);
  padding: 16px 24px;
  gap: 16px;
}

.category-sidebar {
  width: 260px;
  flex-shrink: 0;
}

.category-card {
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.category-card :deep(.ant-card-head) {
  padding: 0 16px;
}

.category-card :deep(.ant-card-body) {
  padding: 16px 0;
}

.category-menu {
  border-right: none;
}

.category-menu-item {
  margin: 4px 0;
  border-radius: 0 20px 20px 0;
}

.category-name {
  margin-right: 8px;
}

.document-panel {
  flex: 1;
  border-radius: 8px;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  padding: 16px;
  overflow: auto;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.search-input {
  width: 300px;
}

.documents-table {
  margin-top: 8px;
}

.documents-table :deep(.ant-table-thead > tr > th) {
  background: #f5f7fa;
  color: #5c6b77;
}

.documents-table :deep(.ant-table-row:hover) {
  background: rgba(24, 144, 255, 0.05);
}

.analytics-panel {
  padding: 24px;
  height: calc(100vh - 165px);
  overflow: auto;
}

.stats-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  flex: 1;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.analytics-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.analytics-card {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  height: 100%;
}

.status-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.category-stat-item {
  margin-bottom: 16px;
}

.category-name {
  font-size: 14px;
  margin-bottom: 4px;
}

.category-bar-container {
  display: flex;
  align-items: center;
  height: 24px;
}

.category-bar {
  height: 100%;
  border-radius: 12px;
  transition: width 0.5s;
}

.category-value {
  margin-left: 8px;
  font-weight: 500;
}

.upload-modal :deep(.ant-modal-body) {
  padding: 24px;
}

.upload-dragger {
  padding: 16px;
}

.preview-modal :deep(.ant-modal-body) {
  padding: 24px;
}

.document-preview {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.document-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-label {
  font-weight: 500;
  margin-right: 8px;
  color: #5c6b77;
}

.document-content-preview {
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.empty-docs {
  padding: 40px 0;
}
</style> 